package com.market.fleamarket.service;

import com.market.fleamarket.entity.Order;
import com.market.fleamarket.entity.Product;
import com.market.fleamarket.entity.User;
import com.market.fleamarket.repository.OrderRepository;
import com.market.fleamarket.repository.ProductRepository;
import com.market.fleamarket.repository.ReviewRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class OrderService {
    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private ReviewRepository reviewRepository;

    @Autowired
    private ProductService productService;

    public List<Order> findAll() {
        return orderRepository.findAll();
    }

    public List<Order> findByBuyerId(Long buyerId) {
        return orderRepository.findByBuyerId(buyerId);
    }

    public Page<Order> findBySellerId(Long sellerId, Pageable pageable) {
        return orderRepository.findByProductUserId(sellerId, pageable);
    }

    public Optional<Order> findById(Long id) {
        return orderRepository.findById(id);
    }

    @Transactional
    public Order updateStatus(Long id, String status) {
        Order order = orderRepository.findById(id).orElseThrow(() -> new RuntimeException("订单不存在"));
        String oldStatus = order.getStatus();
        order.setStatus(status);

        // 如果订单状态变为已完成，不再将商品状态更新为已售出
        // 因为现在商品可以有多个库存，只有当库存为0时才标记为售罄

        // 如果订单状态从pending变为cancelled，需要恢复商品库存
        if ("cancelled".equals(status) && "pending".equals(oldStatus)) {
            Product product = order.getProduct();
            if (product != null) {
                // 恢复库存
                productService.increaseStock(product.getId(), order.getQuantity());
            }
        }

        return orderRepository.save(order);
    }

    @Transactional
    public void deleteOrder(Long id) {
        Order order = orderRepository.findById(id).orElseThrow(() -> new RuntimeException("订单不存在"));

        // 如果订单状态是pending，需要恢复商品库存
        if ("pending".equals(order.getStatus())) {
            Product product = order.getProduct();
            if (product != null) {
                // 恢复库存
                productService.increaseStock(product.getId(), order.getQuantity());
            }
        }

        // 直接删除订单，评价会保留，但order_id会被设置为NULL
        orderRepository.deleteById(id);
    }

    /**
     * 创建新订单
     * @param order 订单信息
     * @return 创建的订单
     */
    @Transactional
    public Order createOrder(Order order) {
        // 检查商品是否存在且有足够库存
        Product product = productRepository.findById(order.getProduct().getId())
                .orElseThrow(() -> new RuntimeException("商品不存在"));

        if (!productService.checkStock(product.getId(), order.getQuantity())) {
            throw new RuntimeException("商品库存不足");
        }

        // 减少商品库存
        productService.decreaseStock(product.getId(), order.getQuantity());

        // 设置订单状态为待处理
        order.setStatus("pending");

        // 保存订单
        return orderRepository.save(order);
    }

    /**
     * 验证用户是否有权限操作订单
     * @param orderId 订单ID
     * @param user 当前用户
     * @param isSeller 是否作为卖家验证
     * @return 订单对象
     * @throws RuntimeException 如果没有权限
     */
    public Order validateOrderAccess(Long orderId, User user, boolean isSeller) {
        Order order = orderRepository.findById(orderId)
                .orElseThrow(() -> new RuntimeException("订单不存在"));

        if (isSeller) {
            // 验证卖家权限
            if (order.getProduct() == null || order.getProduct().getUser() == null ||
                    !order.getProduct().getUser().getId().equals(user.getId())) {
                throw new RuntimeException("您没有权限操作此订单");
            }
        } else {
            // 验证买家权限
            if (order.getBuyer() == null || !order.getBuyer().getId().equals(user.getId())) {
                throw new RuntimeException("您没有权限操作此订单");
            }
        }

        return order;
    }
}